<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="roleName">
              <el-input v-model="searchForm.roleName" :clearable="true" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-form-item prop="roleType">
              <el-select v-model="searchForm.roleType" :clearable="true" placeholder="请选择角色类型">
                <el-option key="1" label="系统" value="1"></el-option>
                <el-option key="2" label="H5" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="100"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="descriptions" label="角色描述"></el-table-column>
        <el-table-column label="角色类型" width="200">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="plain" :type="formatTypes(scope.row.roleType)">
                {{ formatType(scope.row.roleType) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionListAuth" @click.native="handleClickPermiss(scope.row)">权限设置</el-dropdown-item>
                  <el-dropdown-item v-has="permissionListUser" @click.native="handleClickUser(scope.row)">用户设置</el-dropdown-item>
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!-- 用户设置弹出框 -->

    <el-dialog :visible.sync="visible" title="用户信息" width="700px" align="center">
      <el-table border :data="dialogTableList" style="width: max-content">
        <el-table-column label="序号" type="index" align="center" width="100"> </el-table-column>
        <el-table-column label="登录名" prop="userName" align="center" width="200"> </el-table-column>
        <el-table-column label="用户名" prop="nickName" align="center" width="200"> </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button size="mini" v-has="permissionDeleteUser" @click="handleDeleteUser(scope.row.userId, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import AuthApi from '@/api/system/auth';
import * as message from '@/constants/message';

export default {
  name: 'RoleManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      tableList: [],
      dialogTableList: [],
      searchForm: {
        roleName: '',
        roleType: '',
      },
      visible: false,

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      permissionCheck: 'SYSTEM_MANAGER_SYS_ROLE_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_SYS_ROLE_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_SYS_ROLE_LIST_EDIT',
      permissionListAuth: 'SYSTEM_MANAGER_SYS_ROLE_LIST_AUTH',
      permissionListUser: 'SYSTEM_MANAGER_SYS_ROLE_LIST_USER',
      permissionDelete: 'SYSTEM_MANAGER_SYS_ROLE_LIST_DELETE',
      permissionDeleteUser: 'SYSTEM_MANAGER_SYS_ROLE_DELETE_USER',
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  watch: {
    //to去哪，from从哪来
    $route(to, from) {
      if (from.path == '/sys/roleAdd' || from.path == '/sys/roleEdit') {
        this.listTable();
      }
    },
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
    if (this.$route.params.roleId) {
      let userItem = this.tableList.filter((item) => {
        return item.roleId == this.$route.params.roleId;
      });
      let index = this.tableList.indexOf(userItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listTable();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    formatType(cellValue) {
      if (cellValue == 1) {
        return '系统';
      } else if (cellValue == 2) {
        return 'H5';
      }
    },
    formatTypes(cellValue) {
      if (cellValue == 1) {
        return '';
      } else if (cellValue == 2) {
        return 'warning';
      }
    },
    handleClickAdd(row) {
      this.$router.push({ path: '/sys/roleAdd' });
    },
    handleClickDetail(row) {
      this.$router.push({ path: '/sys/roleDetail', query: { id: row.roleId } });
    },
    handleClickEditor(row) {
      this.$router.push({ path: '/sys/roleEdit', query: { id: row.roleId } });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        AuthApi.deleteRole({ id: row.roleId, state: 1 }).then((res) => {
          this.listTable();
          this.$message({
            type: 'success',
            message: message.MSG_ACTION_SUCCESS,
          });
        });
      });
    },

    // 用户设置
    handleClickUser(row) {
      this.roleId = row.roleId;
      AuthApi.getListUserByRoleId({ roleId: row.roleId }).then((res) => {
        this.dialogTableList = res.data;
        this.visible = true;
      });
    },
    // 删除用户
    handleDeleteUser(userId, index) {
      let _this = this;
      _this
        .$confirm('确定删除当前角色下的该用户？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        })
        .then((res) => {
          // let query = `?adminId=${adminId}&roleId=${this.roleId}`

          let params = {
            userId: userId,
            roleId: this.roleId,
          };
          AuthApi.deleteUserRole(params).then((res) => {
            _this.$message({
              type: 'success',
              message: '删除成功',
            });
            _this.dialogTableList.splice(index, 1);
          });
        });
    },
    handleClickPermiss(row) {
      this.$router.push({ path: '/sys/roleMenus', query: { id: row.roleId, roleType: row.roleType, roleName: row.roleName } });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        roleName: this.searchForm.roleName,
        roleType: this.searchForm.roleType,
      };
      this.fetchData(data);
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    fetchData(data) {
      this.$emit('show-loading', true);
      AuthApi.listRole(data).then((res) => {
        this.tableList = res.data.list;
        this.page.pageTotal = res.data.total;
        this.$emit('show-loading', false);
      });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
